import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

import 'package:lottie/lottie.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';
import '../../util.dart';
import 'refresh.dart';
import 'table_man.dart';
import 'section.dart';

class PositionedTableView extends StatelessWidget {
  PositionedTableView({
    Key? key,
    required this.data,
    this.header,
    this.footer,
    this.controller,
    this.listener,
    this.physics,
    this.shrinkWrap = false,
    this.separatorIndent,
    this.padding,
    this.refreshController,
    this.onRefresh,
    this.onLoading,
    this.refreshTopInset,
    this.hasSeprator = true,
  }) : super(key: key) {
    man.getCount(data, hasHeader: header != null, hasFooter: footer != null);
  }
  final List<SectionModel> data;
  final Widget? header;
  final Widget? footer;
  final ItemScrollController? controller;
  final ItemPositionsListener? listener;
  final double? separatorIndent;
  final ScrollPhysics? physics;
  final bool? shrinkWrap;
  final RefreshController? refreshController;
  final VoidCallback? onRefresh;
  final VoidCallback? onLoading;
  final TableMan man = TableMan();
  final EdgeInsets? padding;
  final double? refreshTopInset;
  final bool hasSeprator;

  @override
  Widget build(BuildContext context) {
    if (refreshController == null) {
      return getList();
    }
    return SmartRefresher(
      controller: refreshController!,
      // header: RefreshHeaderFooter.classicHeader(),
      header: RefreshHeaderFooter.customHeader(topInset: refreshTopInset),
      // footer: RefreshHeaderFooter.classicFooter(),
      onRefresh: onRefresh,
      onLoading: onLoading,
      enablePullDown: onRefresh != null,
      enablePullUp: onLoading != null,
      child: getList(),
    );
  }

  Widget getItem(BuildContext context, int index) {
    man.initItems(context, data, header, footer);
    return man.items[index];
  }

  Widget getList() {
    return ScrollablePositionedList.separated(
        physics: physics,
        shrinkWrap: shrinkWrap ?? false,
        itemScrollController: controller,
        itemPositionsListener: listener,
        padding: padding,
        itemBuilder: (context, index) {
          return getItem(context, index);
        },
        separatorBuilder: (context, index) {
          if (index == 0 || !hasSeprator) {
            return const SizedBox();
          }
          return Container(
            margin: EdgeInsets.symmetric(horizontal: separatorIndent ?? 0),
            height: 1.r,
            color: ColorsUtil.separator,
          );
        },
        itemCount: man.count);
  }
}
